/*
 * @Description:
 * @Author: 刘相卿
 * @Company: 山东方亚信息技术有限公司
 * @Date: 2020-09-30 09:09:11
 * @LastEditTime: 2020-09-30 17:17:43
 * @LastEditors: 刘相卿
 */
const Koa = require('koa')
const Router = require('koa-router')
const cors = require('koa2-cors');
const fs = require('fs')

var koaBody = require('koa-body')

const app = new Koa()
const router = new Router()
const mockData = {} //mock数据

const path = require('path')
app.use(cors());
app.use(koaBody()).use(router.routes())
app.use(async (ctx) => {
  // console.log(ctx.request)
  // the parsed body will store in ctx.request.body
  // if nothing was parsed, body will be an empty object {}
  ctx.body = 'hello koa2'

  cors({
    origin: function(ctx) { //设置允许来自指定域名请求
        if (ctx.url === '/appApi') {
            return '*'; // 允许来自所有域名请求
        }
        return 'http://localhost:8080'; //只允许http://localhost:8080这个域名的请求
    },
    maxAge: 5, //指定本次预检请求的有效期，单位为秒。
    credentials: true, //是否允许发送Cookie
    allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], //设置所允许的HTTP请求方法
    allowHeaders: ['Content-Type', 'Authorization', 'Accept'], //设置服务器支持的所有头信息字段
    exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'] //设置获取其他自定义字段
  })
})

// app.use(async ctx => {
//   ctx.body = `Request Body: ${JSON.stringify(ctx.request.body)}`;
// });
function isFileExists(filePath) {
  const stat = fs.lstatSync(filePath)
  return stat.isDirectory()
}

//读取mock目录下的所有文件，组装mockeDemo
function readMockDir(dir) {
  fs.readdirSync(dir).forEach((file) => {
    let _path = path.join(dir + '/' + file)
    if (isFileExists(_path)) {
      readMockDir(_path)
    } else {
      Object.assign(mockData, require(_path))
    }
  })
}
readMockDir(path.join(__dirname + '/mock'))

// console.log(mockData)
for (let key in mockData) {
  let _key = key.replace(/(^\s*)|(\s*$)/g, '')
  let _method = 'get'
  let _url = _key.replace(/^(get|post|put|delete)\s*/i, (rs, $1) => {
    _method = $1.toLowerCase()
    return ''
  })
  router[_method](_url, mockData[key]) //挂载到路由
}
app.listen(3001, () => {
  console.log('mock3001端口已启动')
})
